## SFI doesn't have a public API but uses a very easy to import HTML.
require 'date'

module Shin
  module Data
    class Sfi
      
      def new
        self
      end
      
      # Search (on title)
      def search(params={})
        raise MissingArgument, "You are missing the argument 'title' which is required to use this source." unless params[:title] != ""
        
        params[:type] ||= "MovieTitle"
        params[:match] ||= "Begin"
        params[:year] ||= nil

        # Response
        response = Base.get('http://www.sfi.se/sv/svensk-filmdatabas/sokresultat/?searchword=' + URI.encode(params[:title]) + '&type=' + params[:type] + '&match=' + params[:match] + '&prom=False')
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Nokogiri parse
        @main_noko = Nokogiri::HTML response.body rescue nil
        
        # Can't be nil
        if @main_noko != nil
          @array = []
          
          @main_noko.css('div.search_result > div.search_heading').map do |e|
            @id = e.css('a')[0]['href'][/itemid\=(\d+)/, 1].to_i rescue nil
            
            @title = e.css('a').text.strip rescue nil
            @year = e.text[/\((\d+)/, 1].to_i rescue nil
            @country = e.text[/\((\d+), (.*)\)/, 2].to_s rescue nil
            
            # Find one or get all? (Allow years to be one less or one more aswell)
            if params[:year] == nil
              @array << {id: @id.to_i, title: @title, year: @year, country: @country}
            elsif @year == params[:year] or (@year - 1) == params[:year] or (@year + 1) == params[:year]
              # It should only return a single one if you have specified a year
              return {id: @id.to_i, title: @title, year: @year, country: @country}.to_hashugar
            end
      
          end
          
          # Return
          @array.to_hashugar
        else
          raise NotValid, "Nokogiri failed to parse the HTML."
        end
        
        
      end
      
      # Info
      def info(params={})
        raise MissingArgument, "You are missing the argument 'id' which is required to use this source." unless params[:id] != ""
        
        # Response
        response = Base.get('http://www.sfi.se/sv/svensk-filmdatabas/Item/?type=MOVIE&itemid=' + params[:id].to_s)
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Nokogiri parse
        @main_noko = Nokogiri::HTML response.body rescue nil
        
        # Can't be nil
        if @main_noko != nil
          # Data
          @swedish_title = @main_noko.css('td#ctl00_Full_Main_ctl00_SwedishTitleCell').text.gsub(/Mer$/, "").strip rescue nil
          @description = @main_noko.css('div#ctl00_Full_Main_ctl00_StorySummary').text.strip rescue nil
          @swedish_premiere = @main_noko.css('td#ctl00_Full_Main_ctl00_SwedishPremiereCell').text rescue nil
          @age_limit = @main_noko.css('span#ctl00_Full_Main_ctl00_AgeLimitContent').text.strip rescue nil
          
          {id: params[:id].to_i, swedish_title: @swedish_title, swedish_premiere: @swedish_premiere, description: @description, age_limit: @age_limit}.to_hashugar
        else
          raise NotValid, "Nokogiri failed to parse the HTML."
        end
      end
      
      # Titles
      def titles(params={})
        raise MissingArgument, "You are missing the argument 'id' which is required to use this source." unless params[:id] != ""
        
        # Response
        response = Base.get('http://www.sfi.se/en-GB/svensk-filmdatabas/Item/?type=MOVIE&iv=Titles&itemid=' + params[:id].to_s)
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Nokogiri parse
        @main_noko = Nokogiri::HTML response.body rescue nil
        
        # Can't be nil
        if @main_noko != nil
          @array = []
          
          @main_noko.css('table#ctl00_Full_Main_ctl00_TitlesTable > tr').map do |e|
            @type = e.css('th').text.strip.gsub(/\:$/, "") rescue nil
            @title = e.css('td').text.strip rescue nil
                
            @array << {type: @type, title: @title}
          end
          
          @array.to_hashugar
        else
          raise NotValid, "Nokogiri failed to parse the HTML."
        end
      end
      
      
      # Errors
      class NotValid         < StandardError; end
      class HTTPError        < StandardError; end
      class MissingArgument  < StandardError; end
    end
  end
end